import React, { useEffect, useState } from 'react';
import styles from './style/index.module.less';
import { Table, Select, TableColumnProps, Card, Space, Button,Drawer,Form,Input,InputNumber, Notification  } from '@arco-design/web-react';
import { v4 as uuidv4 } from 'uuid';
import { confirmDelete } from '@/utils/util';

import { ReadSync,SaveSync,DeleteSync } from '@/store/sync';
import { ReadDatasource } from '@/store/datasource';
import { useHistory } from 'react-router-dom';

const Option = Select.Option;

const formItemLayout = {
  wrapperCol: {
    span: 24,
  },
};
function getColumns(
  callback: (record: Record<string, any>, type: string) => Promise<void>
) {
  return [
    {
      title: '源',
      dataIndex: 'fromName',
    },
    {
      title: '目标',
      dataIndex: 'toName',
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 240,
      render: (v, record) => (
        <>
          <Button type="text" size="small" onClick={() => callback(record, 'sync')}>同步</Button>
          <Button type="text" size="small" onClick={() => callback(record, 'edit')}>编辑</Button>
          <Button type="text" size="small" onClick={() => callback(record, 'delete')}>删除</Button>
        </>
      ),
    },
  ];
}

function SyncPage() {
  const history = useHistory();
  const [data,setData] = useState([])
  const [datasource,setDatasource] = useState([])
  const [title,setTitle] = useState('')
  const [visible,setVisible] = useState(false)

  const [editForm] = Form.useForm();
  
  useEffect(() => {
    setDatasource(ReadDatasource())
    let syncArr = ReadSync()
    console.log(syncArr)
    setData(syncArr)
  }, []);
  const tableCallback = async (record, type) => {
    console.log(record)
    if('edit'===type){
      onAddEdit(record.id)
    }else if('delete'==type){
      confirmDelete('确定要删除同步配置吗',()=>{
        doDelete(record.id)
      })
    }else if('sync'==type){
      history.push('/dosync?id=' + record.id)
    }
  };
  const doDelete = (id)=>{
    DeleteSync(id)
    setData(ReadSync())
    Notification.info({position: 'bottomLeft',content:'删除成功！'})
  }

  const onOk =()=>{
    let  item = editForm.getFieldsValue()
    SaveSync(item)
    setData(ReadSync())
    Notification.info({
      position: 'bottomLeft',
      content: '添加成功'
    })
    setVisible(false)
  }
  const onAddEdit = (id)=>{
    data.map((val)=>{
      if (id==val.id){
        editForm.setFieldsValue(val)
        setVisible(true)
        setTitle('编辑同步配置')
      }
    })
  }
  const add =()=>{
    let addData = {id:uuidv4(),from:'',to:'',fromName:'',toName:''}
    editForm.setFieldsValue(addData)
    setTitle('添加同步配置')
    setVisible(true)
  }
  return (
    <div className={styles.container}>
      <Card style={{ width: '100%' }} title='同步表结构' extra={
        <Space>
          <Button size='small' type='primary' onClick={add}>添加</Button>
        </Space>
      }>
        <Table
          rowKey='id'
          columns={getColumns(tableCallback)}
          data={data}
          pagination={false}
          size='small'
        />
      </Card>
      <Drawer
        width={600}
        title={title}
        visible={visible}
        maskClosable={false}
        onOk={onOk}
        onCancel={() => {
          setVisible(false);
        }}
      >
      <Form {...formItemLayout} form={editForm} layout='vertical'>
        <Form.Item hidden={true} field='id'><Input /></Form.Item>
        <Form.Item label='源' field='from' rules={[{ required: true }]}>
          <Select placeholder='选择源'>
          {datasource.map((value) => (
            <Option key={value.id} value={value.id}>
              {value.name}
            </Option>
          ))}
          </Select>
        </Form.Item>
        <Form.Item label='目标' field='to' rules={[{ required: true }]}>
        <Select placeholder='选择目标'>
          {datasource.map((value) => (
            <Option key={value.id} value={value.id}>
              {value.name}
            </Option>
          ))}
          </Select>
        </Form.Item>
      </Form>
      </Drawer>
    </div>
  );
}

export default SyncPage;
